var app = getApp();
// pages/order/downline.js
Page({
  data: {
    itemData: {},
    userId: 0,
    pulldown: false,
    remark: '',
    minusStatuses:[],
    cartId: 0,
    addrId: 0,//收货地址//测试--
    btnDisabled: false,
    productData: [],
    address: {}, 
    total: 0,
    vprice: 0,
    yunfei: 0,
    vid: 0,
    addemt: 1,
    vou: [],
    flag: 0,
    flag1: 0,
    OK:false,
    jyflag:0,
    code:0,
    is_pd:0,
    patients:[],
    pati_id:0,
    srcs:0,
    currentTab: 0,
    /**      * 页面配置      */
    winWidth: 0, winHeight: 0,
    sxiala:0,
    fxiala:0,
    group_flag:0,
    group_id:0,
    group_pics:[],
  },
  onLoad: function (options) {
    var that=this
    if (app.globalData.froms == 'user') {
      wx.setNavigationBarColor({
        frontColor: 'white',
        backgroundColor: '#e93d3b',
      })
    } else {
      wx.setNavigationBarColor({
        frontColor: 'white',
        backgroundColor: '#e93d3b',
      })
    }
    that.setData({
        winHeight: 1014+150*2
    })
    var uid = app.d.userId;
    console.log(options)
    if(options.group_flag){
      that.setData({
        group_flag: options.group_flag,
        group_id: options.group_id,
      })
      that.loadPic();
    }
    console.log((typeof options.DATAs) != "undefined")
    
    if ((typeof options.DATAs) != "undefined") {
    var DAta = options.DATAs.split(",")
    console.log((typeof options.DATA) != "undefined")
    this.setData({
      cartId: DAta[DAta.length-1],
      userId: uid, 
    })
    DAta.splice(DAta.length-1,1)
   var buff=DAta
console.log(buff)
    this.setData({
      buff:buff,
      HAVE:true
    })
    }else{
      this.setData({
        cartId: options.cartId,
        userId: uid,
        HAVE:true//这里不知道啥原来为false
      })
    }
    this.loadProductDetail();
    this.loadCoin();
    setTimeout(function(){
        console.log(that.data.productData)
        console.log(that.data.productData.length)
    if(that.data.pulldownjy){
        sxiala:58
    }
    if(that.data.productData.length>1){
        fxiala:58
    }
    that.setData({
            winHeight: 1010+300+that.data.fxiala+that.data.sxiala
     })
 
        for (var i = 0; i < that.data.productData.length; i++) {
          if (that.data.productData[i].num == 1) {
            that.setData({
              minusStatuses: that.data.minusStatuses.concat('disabled')
        })
          } else if (that.data.productData[i].num > 1) {
            that.setData({
              minusStatuses: that.data.minusStatuses.concat('normal')
        })
      }
      console.log(i)
    }
        console.log(that.data.minusStatuses)
    },2000)

  },
  loadProductDetail: function () {
    var that = this;
     if(that.data.group_flag){
           var url1=app.d.ceshiUrl + '/Api/Group/buy_cart'
        }else{
           var url1=app.d.ceshiUrl + '/Api/Payment/buy_cart'
        }
    if(this.data.HAVE){
      wx.request({
        url: url1,
        method: 'post',
        data: {
          cart_id: that.data.cartId,
          uid: that.data.userId,
          buff: that.data.buff,
          group_flag:that.data.group_flag
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          var adds = res.data.adds; 
          var pdata = res.data.pdata; 
          var jyflag = res.data.jyflag; 

          if (adds) {
            var addrId = adds.id;
            that.setData({
              address: adds,
              addrId: addrId
            });
          }
          if(pdata){
            var pat_id = pdata.id;
            that.setData({
              patients: pdata,
              pati_id: pat_id
            });
          }
          that.setData({
            addemt: res.data.addemt,
            productData: res.data.pro,
            total: res.data.gprice,
            vprice: res.data.price,
            vou: res.data.vou,
            yunfei: res.data.yunfei,
            jyflag:jyflag,
            is_pd:res.data.is_pd
          })
          console.log(that.data.is_pd);
          if(res.data.is_pd==1){
              wx.setNavigationBarTitle({
                 title: '填写预约单'
              })
          }
  
        }
      })
    }else{
      wx.request({
        url: url1,
        method: 'post',
        data: {
          cart_id: that.data.cartId,
          uid: that.data.userId,
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res.data)
          var adds = res.data.adds;
          if (adds) {
            var addrId = adds.id;
            that.setData({
              address: adds,
              addrId: addrId
            });
          }
          that.setData({
            addemt: res.data.addemt,
            productData: res.data.pro,
            total: res.data.gprice,
            vprice: res.data.price,
            vou: res.data.vou,
            yunfei: res.data.yunfei
          })
        }
      })
    }
  },
  loadCoin: function () {
    console.log(app.d.userId)
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Company/num_list',
      method: 'post',
      data: {
        uid: app.d.userId
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res)
        that.setData({
          num: res.data.num
        })
      },
      fail: function (e) {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      }
    })
  },
  remarkInput: function (e) {
    this.setData({
      remark: e.detail.value,
    })
  },
  changePulldown: function () {
    
    if (this.data.pulldown) {
      this.setData({
        pulldown: false,
        winHeight:this.data.winHeight-300*(this.data.productData.length-1)
      })
    } else {
      this.setData({
        pulldown: true,
        winHeight:this.data.winHeight+300*(this.data.productData.length-1)
      })
    }
  },
  changePulldownjy: function () {
    
    if (this.data.pulldownjy) {
      this.setData({
        pulldownjy: false,
        winHeight:this.data.winHeight-64
      })
    } else {
      this.setData({
        pulldownjy: true,
        winHeight:this.data.winHeight+64
      })
    }
  },
  bindMinus: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.productData[index].num;
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num--;
    }
    console.log(num);
    if(that.data.group_flag){
           var url2=app.d.ceshiUrl + '/Api/Shopping/upCartGroup'
        }else{
           var url2=app.d.ceshiUrl + '/Api/Shopping/up_cart'
     }
    wx.request({
      url: url2,
      method: 'post',
      data: {
        user_id: app.d.userId,
        num: num,
        cart_id: that.data.productData[index].cart_id
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var status = res.data.status;
        if (status == 1) {
          // 只有大于一件的时候，才能normal状态，否则disable状态
          var minusStatus = num <= 1 ? 'disabled' : 'normal';
          // 购物车数据
          var productData = that.data.productData;
          productData[index].num = num;
          that.setData({
            productData: productData
          })
          // 按钮可用状态
          var minusStatuses = that.data.minusStatuses;
          minusStatuses[index] = minusStatus;
          // 将数值与状态写回
          that.setData({
            minusStatuses: minusStatuses
          });
          that.reLoadProductDetail();
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      }
    });
  },
  bindManual:function(e){
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = e.detail.value;
    if(num>=1){
     if(that.data.group_flag){
           var url2=app.d.ceshiUrl + '/Api/Shopping/upCartGroup'
        }else{
           var url2=app.d.ceshiUrl + '/Api/Shopping/up_cart'
     }
      wx.request({
        url: url2,
        method: 'post',
        data: {
          user_id: app.d.userId,
          num: num,
          cart_id: that.data.productData[index].cart_id
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          var productData = that.data.productData;
          productData[index].num = num;
          that.setData({
            productData: productData,
            OK: false
          })
          that.reLoadProductDetail();
        },
        fail: function () {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        }
      });
    }else{
      wx.showToast({
        title: '请输入合理的数量',
        icon:'none'
      });
      this.setData({
        OK:true
      })
    }
  },
  bindPlus: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.productData[index].num;
    // 自增
    num++;
    console.log(num);
    if(that.data.group_flag){
           var url2=app.d.ceshiUrl + '/Api/Shopping/upCartGroup'
        }else{
           var url2=app.d.ceshiUrl + '/Api/Shopping/up_cart'
     }
    wx.request({
      url: url2,
      method: 'post',
      data: {
        user_id: app.d.userId,
        num: num,
        cart_id: that.data.productData[index].cart_id
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var status = res.data.status;
        if (status == 1) {
          // 只有大于一件的时候，才能normal状态，否则disable状态
          var minusStatus = num <= 1 ? 'disabled' : 'normal';
          var productData = that.data.productData;
          productData[index].num = num;
          that.setData({
            productData: productData
          })
          var minusStatuses = that.data.minusStatuses;
          minusStatuses[index] = minusStatus;
          that.setData({
            minusStatuses: minusStatuses
          });
        that.reLoadProductDetail();
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function () {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      }
    });
  },
  reLoadProductDetail: function () {
    var that = this;
    if(that.data.group_flag){
           var url1=app.d.ceshiUrl + '/Api/Group/buy_cart'
        }else{
           var url1=app.d.ceshiUrl + '/Api/Payment/buy_cart'
    }
    if (this.data.HAVE) {
      wx.request({
        url: url1,
        method: 'post',
        data: {
          cart_id: that.data.cartId,
          uid: that.data.userId,
          buff: that.data.buff,
          group_flag:that.data.group_flag
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          that.setData({
            total: res.data.gprice,
            vprice: res.data.price,
            yunfei: res.data.yunfei,
          })
        }
      })
    } else {
    if(that.data.group_flag){
           var url1=app.d.ceshiUrl + '/Api/Group/buy_cart'
        }else{
           var url1=app.d.ceshiUrl + '/Api/Payment/buy_cart'
    }
      wx.request({
        url: url1,
        method: 'post',
        data: {
          cart_id: that.data.cartId,
          uid: that.data.userId,
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          that.setData({
            total: res.data.gprice,
            vprice: res.data.price,
            yunfei: res.data.yunfei,
          })
        }
      })
    }
  },
  //选择优惠券
  getvou: function (e) {
    var that=this;
    var vid = e.currentTarget.dataset.id;
    var price = e.currentTarget.dataset.price;
    var zprice = this.data.vprice;
    var cprice = parseFloat(zprice) - parseFloat(price);
    console.log(this.data.vprice);//判断优惠券
    wx.request({
        url: app.d.ceshiUrl + '/Api/Payment/fank_voucher',
        method: 'post',
        data: {
          cart_id: that.data.cartId,
          vid:vid,
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          console.log(res);
          if(res.data.status==1){
             that.setData({
              total: res.data.data.goodp,
              vprice: res.data.data.goodp,
              vid: vid,
             })
          }else{
               that.reLoadProductDetail();
          }


        }
      })

  },
  //使用健康币
  useCoin: function (e) {
    var that = this
    var code = e.currentTarget.id
    this.setData({
      code:code
    })
    console.log(code)
    if (code == 'gold') {
      if (this.data.flag == 0) {
        this.setData({
          cgold: e.currentTarget.dataset.price,
          cygold: 0,
          flag: 1,
          flag1: 0,
        })
      } else {
        this.setData({
          cgold: 0,
          cygold: 0,
          flag: 0,
          code:''
        })
      }
      this.setData({
        discount: this.data.cgold
      })
    } else {
      if (this.data.flag1 == 0) {
        this.setData({
          cgold: 0,
          cygold: e.currentTarget.dataset.price,
          flag1: 1,
          flag: 0
        })
      } else {
        this.setData({
          cgold: 0,
          cygold:0,
          flag1: 0,
          code:''
        })
      }
      this.setData({
        discount: this.data.cygold
      })
    }

    var zprice = this.data.total+this.data.yunfei;
    console.log(zprice)
    console.log(this.data.discount)
    console.log(zprice > this.data.discount)
    if (zprice >= this.data.discount) {
      var cprice = (zprice - this.data.discount).toFixed(2);
      console.log(cprice)
      if(cprice>0&&this.data.discount!=0){
        this.setData({
          FLAg: false,
         
        })
      }else{
        this.setData({
          FLAg: false,
          vprice: cprice,
        })
      }

      console.log(this.data.vprice)
    } else {
      this.setData({
        FLAg: true
      })
    }

  },
  //微信支付
  createProductOrderByWX: function (e) {
    this.setData({
      paytypes: 'weixin',
    });
    this.createProductOrder();
  },

  //线下支付
  createProductOrderByXX: function (e) {
    this.setData({
      paytype: 'cash',
    });
    wx.showToast({
      title: "线下支付开通中，敬请期待!",
      duration: 3000
    });
    // return false;

    //未开通 关闭
    // this.createProductOrder();
  },
  //健康币支付
  createProductOrderByJJ: function (e) {
    if (this.data.flag == 0 && this.data.flag1 == 0) {
      wx.showToast({
        title: '请先选择健康币',
      })
    } else {
      console.log(this.data.flag);
      console.log(this.data.flag1);
      console.log('ceshi');
      if (this.data.flag == 1) {
        this.setData({
          paytype: 'gold',
        });
      }
      if (this.data.flag1 == 1) {
        this.setData({
          paytype: 'ygold',
        });
      }

      this.createProductOrderJK();
    }
  },
  //确认订单(健康币)
  createProductOrderJK: function () {
    this.setData({
      btnDisabled: false,
    })
    //创建订单
    var that = this;
    var zprice = this.data.vprice;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Payment/payment',
      method: 'post',
      data: {
        uid: that.data.userId,
        cart_id: that.data.cartId,
        buff: that.data.buff,
        type: that.data.paytype,
        aid: that.data.addrId,//地址的id
        remark: that.data.remark,//用户备注
        price: that.data.total,//总价
        vid: that.data.vid,//优惠券ID
        cygold: that.data.cygold,
        cgold: that.data.cgold,
        pati_id:that.data.pati_id,
        srcs:that.data.srcs,
        is_pd:that.data.is_pd
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {  
      console.log(res)   
        var data = res.data;
        if (data.status == 1) {
          //创建订单成功
          if (data.arr.pay_type == 'gold' || data.arr.pay_type == 'ygold') {
            //健康币支付
            // wx.showToast({
            //   title: "支付成功!",
            //   duration: 2000,
            // });
            var zhi =data.arr.zhi;
            setTimeout(function () {
              wx.redirectTo({
                url: '../order_complete/order_complete?price='+ zprice+'&order_sn='+data.order_sn
              });
            }, 1500);
          }
        } else if(data.status == 1002){
             wx.showToast({
                      title:''+res.data.err,
                      icon: 'none',
                      duration: 1500
             });
             setTimeout(function () {
              wx.redirectTo({
                url: '../address/address?cartId='+ that.data.cartId
              });
            }, 1500);

        }else {
          wx.showToast({
            title:''+res.data.err,
            icon: 'none',
            duration: 2500
          });
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '网络不给力！err:createProductOrder',
          duration: 2000
        });
      }
    });
  },
  //确认订单(微信)
  createProductOrder: function () {
    this.setData({
      btnDisabled: false,
    })
    if(this.data.group_flag){
        var url3=app.d.ceshiUrl + '/Api/Group/payment'
    }else{
        var url3=app.d.ceshiUrl + '/Api/Payment/payment'
    }
    if(this.data.code==''){
        //创建订单
        var that = this;
        wx.request({
          url: url3,
          method: 'post',
          data: {
            uid: that.data.userId,
            cart_id: that.data.cartId,
            buff: that.data.buff,
            type: that.data.paytypes,
            aid: that.data.addrId,//地址的id
            remark: that.data.remark,//用户备注
            price: that.data.total,//总价
            vid: that.data.vid,//优惠券ID
            ctype: that.data.code,
            cygold: that.data.cygold,
            cgold: that.data.cgold,
            jyflag:that.data.jyflag,
            pati_id:that.data.pati_id,
            srcs:that.data.srcs,
            is_pd:that.data.is_pd,
            group_flag:that.data.group_flag,
            group_id:that.data.group_id
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {     
            var data = res.data;
            if (data.status == 1) {
              //创建订单成功
              if (data.arr.pay_type == 'cash') {
                wx.showToast({
                  title: "请自行联系商家进行发货!",
                  duration: 3000
                });
                return false;
              }
              if (data.arr.pay_type == 'weixin') {
                //微信支付
                that.wxpay(data.arr);
              }
            } else if(data.status == 1002){
             wx.showToast({
                      title:''+res.data.err,
                      icon: 'none',
                      duration: 1500
             });
             setTimeout(function () {
              wx.redirectTo({
                url: '../address/address?cartId='+ that.data.cartId
              });
            }, 1500);
        }else {
              wx.showToast({
                title:''+res.data.err,
                icon:'none',
                duration: 2500
              });
            }
      },
      fail: function (e) {
            wx.showToast({
              title: '网络不给力！err:createProductOrder',
              duration: 2000
            });
      }
     });
    }else{
        wx.showToast({
          title: '健康币不足',
          icon: 'none',
          duration: 2000
        });
    }
  },

  //调起微信支付
  wxpay: function (order) {
    var that=this
    var zprice = this.data.vprice;
    console.log(order)
    wx.request({
      url: app.d.ceshiUrl + '/Api/Wxpay/wxpay',
      data: {
        order_id: order.order_id,
        order_sn: order.order_sn,
        group_flag: order.group_flag,
        uid: this.data.userId,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }, // 设置请求的 header
      success: function (res) {
        if (res.data.status == 1) {
          var order = res.data.arr;
          var order_sn = res.data.order_sn;
          wx.requestPayment({
            timeStamp: order.timeStamp,
            nonceStr: order.nonceStr,
            package: order.package,
            signType: 'MD5',
            paySign: order.paySign,
            success: function (res) {
              console.log(order_sn)
              console.log('wjppay')
              // wx.showToast({
              //   title: "支付成功!",
              //   duration: 2000,
              // });
              setTimeout(function () {
                if(that.data.group_flag){
                    var url4='../order_group/index?price='+ zprice+'&order_sn='+order_sn
                }else{
                    var url4='../order_complete/order_complete?price='+ zprice+'&order_sn='+order_sn
                }
                wx.redirectTo({
                  url: url4
                });
              }, 1500);
            },
            fail: function (res) {
              console.log(res)
              wx.showModal({
                title:'支付失败',
                content: '是否前往支付?',
                success: function (res) {
                  if (res.confirm) {
                    if(that.data.group_flag){
                      wx.redirectTo({
                            url: '../order_group/index?price='+ zprice+'&order_sn='+order_sn,
                         })   
                    }else{
                      wx.redirectTo({
                            url: (app.globalData.froms == 'company_user' ? '../company_user/dingdan?currentTab=0&otype=pay' : '../user/dingdan?currentTab=0&otype=pay'),
                         })                   
                    }

         
                  }else{
                    wx.redirectTo({
                      url: '../product/detail?pro_id='+that.data.productData[0].pid,
                    })
                  }
                }
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function () {
        // fail
        wx.showToast({
          title: '网络不给力！err:wxpay',
          duration: 2000
        });
      }
    })
  },
    chooseImage: function (event) {
    var id = event.target.id;
    console.log(id);
    var that = this;
    wx.chooseImage({
      count: 1, // 一次最多可以选择2张图片一起上传
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var src = res.tempFilePaths;
         wx.showToast({  
                title: '正在上传...',  
                icon: 'loading',  
                mask: true,  
                duration: 5000  
          })  

        wx.uploadFile({  
          url: app.d.ceshiUrl + '/Api/Public/up_images',  
          filePath: src[0],  
          name: 'file',  
          formData: {  
            'uid': that.data.userId,  
          },  
          header: {  
            "Content-Type": "multipart/form-data"  
          },  
          success: function (res) { 
           var data = JSON.parse(res.data);
            console.log(res.data);
            console.log(data.status);
            if(data.status==1){
              that.setData({
                flag3: true,
                srcs: data.msg,
              })
            }else{
               wx.showToast({  
                title: data.msg,  
                icon: 'none',  
                duration: 3000  
                })  
            }

          },  
          fail: function (res) {  
            wx.hideToast();  
            wx.showModal({  
              title: '错误提示',  
              content: '上传图片失败',  
              showCancel: false,   
            })  
          }  
        });  

      }
    })
  },
  loadPic:function(){
    var that=this
    wx.request({
        url: app.d.ceshiUrl + '/Api/Group/groupPic',
        method: 'post',
        data: {
          group_id: that.data.group_id,
          uid: app.d.userId,
          flag: that.data.group_flag
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
            var datas=res.data
            if(datas.code==200){
               that.setData({
                group_pics: datas['data'],
              })
            }
        }
      })
 },
  onShareAppMessage: function () {
    return {
      title: '',
      path: '',
      success: function (res) {
        // 分享成功
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },

});